//
//  VRModifyPwdViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/10.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRModifyPwdViewController.h"

#import "UIImage+VR.h"

@interface VRModifyPwdViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIButton *getVerCodeBtn;

@property (nonatomic, strong) NSMutableArray<UIView *> *inputViewArray;
@property (nonatomic, strong) dispatch_source_t timer;

@property (nonatomic, assign) BOOL isCountDown;

@end

@implementation VRModifyPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"修改密码";
    self.view.backgroundColor = ScrollViewBgColor;
    
    self.inputViewArray = [NSMutableArray array];
    
    [self setupSubView];
}

- (void)setupSubView
{
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 30);
        make.width.mas_equalTo(kScreenWidth);
        //        make.height.mas_equalTo(200);
    }];
    
    
    NSArray *imgNameArray = @[@"phone_icon", @"login_code", @"login_pwd_gray", @"login_pwd_gray"];
    NSArray *placeholderArray = @[@"请输入手机号", @"请输入短信验证码", @"输入新密码", @"请确认新密码"];
    NSArray *titleArray = @[@"手机号", @"验证码", @"新密码", @"确认密码"];
    for (int i = 0; i < imgNameArray.count; i++) {
        
        UIView *inputView = [[UIView alloc] init];
        inputView.layer.borderColor = RGB(120, 120, 120).CGColor;
        inputView.layer.borderWidth = 1.0;
        inputView.size = CGSizeMake(kScreenWidth - 40, 44);
        [contentView addSubview:inputView];
        
        UIImageView *iconImgView = [[UIImageView alloc] init];
        iconImgView.contentMode = UIViewContentModeScaleAspectFit;
        iconImgView.tag = 1000;
        iconImgView.image = [UIImage imageNamed:imgNameArray[i]];
        iconImgView.frame = CGRectMake(10, 0, 16, 16);
        iconImgView.centerY = 22;
        [inputView addSubview:iconImgView];
        
        UILabel *titleLbl = [[UILabel alloc] init];
        titleLbl.text = titleArray[i];
        titleLbl.textColor = RGB(50, 50, 50);
        titleLbl.font = VRFont(14);
        titleLbl.frame = CGRectMake(CGRectGetMaxX(iconImgView.frame) + 8, 0, 58, 44);
        [inputView addSubview:titleLbl];
        
        UITextField *tf = [[UITextField alloc] init];
        tf.tag = 1001;
        tf.font = VRFont(16);
        tf.textColor = RGB(51, 51, 51);
        [tf setValue:RGB(107, 198, 255) forKeyPath:@"_placeholderLabel.textColor"];
        tf.placeholder = placeholderArray[i];
        tf.frame = CGRectMake(CGRectGetMaxX(titleLbl.frame) + 10, 0, kScreenWidth - CGRectGetMaxX(titleLbl.frame) - 10 - 80, 44);
        tf.delegate = self;
        [tf addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
        [inputView addSubview:tf];
        
        tf.keyboardType = UIKeyboardTypeNumberPad;
        if (i == 0) {
            
            tf.clearButtonMode = UITextFieldViewModeWhileEditing;
            tf.width = kScreenWidth - 132 - 30;
        }else if (i == 1) {
            
            UIButton *getVerCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            getVerCodeBtn.tag = 1003;
            getVerCodeBtn.layer.cornerRadius = 4;
            getVerCodeBtn.layer.masksToBounds = YES;
            [getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [getVerCodeBtn setTitleColor:MAINColor forState:UIControlStateNormal];
            [getVerCodeBtn setTitleColor:RGB(150, 150, 150) forState:UIControlStateDisabled];
            [getVerCodeBtn setBackgroundImage:[UIImage imageWithColor:RGB(101, 183, 224)] forState:UIControlStateNormal];
            [getVerCodeBtn setBackgroundImage:[UIImage imageWithColor:RGB(220, 220, 220)] forState:UIControlStateDisabled];
            getVerCodeBtn.titleLabel.font =  VRFont(12);
//            getVerCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [getVerCodeBtn addTarget:self action:@selector(onGetVerCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [inputView addSubview:getVerCodeBtn];
            getVerCodeBtn.frame = CGRectMake(kScreenWidth - 40 - 70 - 10, 0, 70, 30);
            getVerCodeBtn.centerY = 22;
            self.getVerCodeBtn = getVerCodeBtn;
        }else if (i == 2 || i == 3) {
            
            tf.secureTextEntry = YES;
            tf.keyboardType = UIKeyboardTypeASCIICapable;
            
            // 按钮
//            UIButton *viewPasswordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//            [viewPasswordBtn setImage:[UIImage imageNamed:@"icon_password_visible"] forState:UIControlStateNormal];
//            [viewPasswordBtn setImage:[UIImage imageNamed:@"icon_password_unvisible"] forState:UIControlStateSelected];
//            [viewPasswordBtn addTarget:self action:@selector(onShowPasswordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//            [inputView addSubview:viewPasswordBtn];
//            viewPasswordBtn.frame = CGRectMake(kScreenWidth - 40 - 20 - 30, 0, 30, 20);
//            viewPasswordBtn.centerY = 22;
        }
        
        CGFloat inputViewY = i * 44 + i * 20;
        inputView.frame = CGRectMake(20, inputViewY, kScreenWidth - 40, 44);
        [self.inputViewArray addObject:inputView];
    }
    
    
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo([self.inputViewArray lastObject]);
    }];
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"确定" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onSureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
//    self.loginBtn = loginBtn;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(contentView.mas_bottom).offset(50);
        make.width.mas_equalTo(kScreenWidth - 24);
        make.height.mas_equalTo(46);
    }];
}


- (void)startCountDown
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    weakify(self)
    dispatch_source_set_event_handler(_timer, ^{
        
        strongify(self)
        if(time <= 0){ //倒计时结束，关闭
            
            self.isCountDown = NO;
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                self.getVerCodeBtn.enabled = YES;
                [self.getVerCodeBtn setTitle:@"重新获取" forState:(UIControlStateNormal)];
                [self.getVerCodeBtn setTitleColor:MAINColor forState:UIControlStateNormal];
                [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateDisabled)];
            });
            
        }else{
            
            self.isCountDown = YES;
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.getVerCodeBtn.enabled = NO;
                //                self.isCountdown = YES;
                [self.getVerCodeBtn setTitle:[NSString stringWithFormat:@"%ds", seconds] forState:(UIControlStateDisabled)];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


- (void)stopCountDown
{
    self.isCountDown = NO;
    dispatch_source_cancel(_timer);
}


#pragma mark - networking
- (void)updatePassword
{
    
    UITextField *tf0 = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *tf1 = [self.inputViewArray[1] viewWithTag:1001];
    UITextField *tf2 = [self.inputViewArray[2] viewWithTag:1001];
    UITextField *tf3 = [self.inputViewArray[3] viewWithTag:1001];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = tf0.text;
    param[@"code"] = tf1.text;
    param[@"pwd"] = tf2.text;
    param[@"pwd1"] = tf3.text;
    
    weakify(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:UpdatePassword_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if(msg.length > 0){
            [SVProgressHUD showErrorWithStatus:msg];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}


- (void)getCapcha
{
    
    UITextField *tf0 = [self.inputViewArray[0] viewWithTag:1001];
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    
    NSString *timeStampStr = [NSString stringWithFormat:@"%.0lf", timeStamp];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = tf0.text;
    //    param[@"timestamp"] = timeStampStr;
    
    weakify(self)
    [JKNetworking postWithSign:GetCaptcha_url parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self startCountDown];
            });
        }else if(msg.length > 0){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.getVerCodeBtn.enabled = YES;
                [SVProgressHUD showErrorWithStatus:msg];
            });
        }
    } error:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)onShowPasswordBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    UITextField *tf = [sender.superview viewWithTag:1001];
    
    tf.enabled = NO;
    tf.secureTextEntry = !sender.selected;
    
    tf.enabled = YES;
    [tf becomeFirstResponder];
}

- (void)onGetVerCodeBtnClick:(UIButton *)sender
{
//    [self startCountDown];
    sender.enabled = NO;
    [self getCapcha];
}

- (void)onSureBtnClick:(UIButton *)sender
{
    UITextField *tf0 = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *tf1 = [self.inputViewArray[1] viewWithTag:1001];
    UITextField *tf2 = [self.inputViewArray[2] viewWithTag:1001];
    UITextField *tf3 = [self.inputViewArray[3] viewWithTag:1001];
    
    if (tf0.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    if ([NSString valiMobile:tf0.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    if (tf1.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"验证码不能为空"];
        return;
    }
    if (tf2.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"新密码不能为空"];
        return;
    }
    if (tf3.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"旧密码不能为空"];
        return;
    }
    
    [self updatePassword];
}


#pragma mark - delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    UITextField *tf = [self.inputViewArray[0] viewWithTag:1001];
    if ([string length] > 0) {
        if (textField == tf) {
            
            if (![self deptNumInputShouldNumber:string]) {
                return NO;
            }
            if (textField.text.length >= 11) {
                return NO;
            }
        } else {
            
            //            if (![self deptNumInputShouldNumber:string]) {
            //                return NO;
            //            }
            //            if (textField.text.length >= 6) {
            //                return NO;
            //            }
        }
    }
    return YES;
}


- (void)textFieldTextChanged:(UITextField *)textField
{
    
    UITextField *tf = [self.inputViewArray[0] viewWithTag:1001];
    if (textField == tf) {
        
        self.getVerCodeBtn.enabled = NO;
        
        if (self.isCountDown) {
            [self stopCountDown];
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:(UIControlStateDisabled)];
        }
        
        if (textField.text.length == 11) {
            
            BOOL validate = [textField.text hasPrefix:@"1"];
            self.getVerCodeBtn.enabled = validate;
        }
    }else{
        
        //        if (textField.text.length == 6 && self.usernameTF.text.length == 11) {
        //
        //            self.loginBtn.enabled = YES;
        //        }else{
        //            self.loginBtn.enabled = NO;
        //        }
    }
}


- (BOOL)deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

@end
